package com.wstuo.common.security.utils;

import com.wstuo.common.security.dao.IResourceDAO;
import com.wstuo.common.security.entity.Resource;
import com.wstuo.common.security.entity.Role;
import com.wstuo.common.security.service.EnduserCompetence;
import com.wstuo.common.security.service.IRoleService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;

import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Set;

/**
 * MyWebInvocationPrivilegeEvaluator
 * 
 */
public class MyWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator {
	@Autowired
	private IResourceDAO resourceDAO;
	@Autowired
	private EnduserCompetence enduserCompetence;

	/**
	 * isAllowed
	 * 
	 * @param uri
	 * @param authentication
	 * @return boolean
	 */
	@Transactional
	public boolean isAllowed(String uri, Authentication authentication) {
		Resource resource = resourceDAO.findByResUrl(uri);

		Boolean isAllowed = false;

		if (resource == null) {
			isAllowed = true;
		} else {
			 Set<Role> roles = resource.getRoles( );

//			String[] roleCodes = resource.getRoleCodes();

			Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

			for (GrantedAuthority ga : authorities) {
				String authority = ga.getAuthority();
				for (Role role : roles) {
					String roleCode = role.getRoleCode();
					if (roleCode!=null&&roleCode.equals(IRoleService.ROLE_ENDUSER)) {
						if (enduserCompetence.getCompetences().contains(uri)) {
							isAllowed = true;
							break;
						}
					} else if (roleCode.equals(authority)) {
						isAllowed = true;
						break;
					}
				}
				/*for (String roleCode : roleCodes) {
					if (roleCode.equals(IRoleService.ROLE_ENDUSER)) {
						if (enduserCompetence.getCompetences().contains(uri)) {
							isAllowed = true;
							break;
						}
					} else if (roleCode.equals(authority)) {
						isAllowed = true;
						break;
					}
				}*/
			}
		}

		return isAllowed;
	}

	/**
	 * isAllowed
	 * 
	 * @param contextPath
	 * @param uri
	 * @param method
	 * @return boolean
	 */
	public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) {
		return isAllowed(uri, authentication);
	}
}
